package view.backend.user;

import exceptionManager.ExceptionManager;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
import model.User;
import model.handlers.UserHandler;
import view.generaldesign.DesignLayout;

/**
 *
 * @author Sonny Sandberg
 */
public class AdminUserListPanel extends JPanel
{
    private JTextField 
            tFieldUsername,
            tFieldEmail;
    private JPasswordField 
            pFieldNewPassword,
            pFieldNewPasswordRepeat;
    private JLabel 
            lblAccess,
            lblPasswordMessage;
    private JButton 
            btnNewPassword,
            btnAlterPassword;
    private User userObject;
    private User currentUser;
    private JPanel 
            newPasswordPanel,
            newAccessLevelPanel;
    private AdminUser adminUser;
    
    public AdminUserListPanel(AdminUser view, User user)
    {
        adminUser = view;
        userObject = user;
        try
        {
            currentUser = UserHandler.getUserByID(userObject.getId());
        } 
        catch (SQLException ex)
        {
            ExceptionManager.handleSQLException(ex);
        } 
        catch (ClassNotFoundException ex)
        {
            ExceptionManager.handleClassNotFoundException(ex);
        }
        
        setLayout(null);
        setSize(new Dimension(260, 125));
        setOpaque(false);
        
        newPasswordPanel = newPasswordPanel();
        newPasswordPanel.setBounds(1, 1, 258, 123);
        newPasswordPanel.setVisible(false);
        add(newPasswordPanel);
        
        newAccessLevelPanel = changeAccessLevel();
        newAccessLevelPanel.setBounds(1, 1, 258, 123);
        newAccessLevelPanel.setVisible(false);
        add(newAccessLevelPanel);
        
        // Username Field Begin
        tFieldUsername = new JTextField(user.getUsername());
        tFieldUsername.setBounds(10, 5, 240, 20);
        tFieldUsername.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        tFieldUsername.setBorder(null);
        tFieldUsername.setEditable(false);
        tFieldUsername.setOpaque(false);
        tFieldUsername.addMouseListener(new MouseAdapter() 
        {
            @Override
            public void mouseReleased(MouseEvent evt)
            {
                tFieldUsername.setEditable(true);
                tFieldUsername.setForeground(Color.ORANGE);
                tFieldUsername.getCaret().setVisible(true);
            }
        });
        
        tFieldUsername.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                try
                {
                    boolean usernameAvailable = false;
                    userObject.setUsername(tFieldUsername.getText());
                    if (tFieldUsername.getText().length() > 0)
                    {
                        usernameAvailable = UserHandler.isUsernameAvailable(userObject);
                    }
                    else
                    {
                        usernameAvailable = false;
                    }
                    if (usernameAvailable == true)
                    {
                        tFieldUsername.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                    }
                    else
                    {
                        if (currentUser.getUsername().equals(userObject.getUsername()))
                        {
                            tFieldUsername.setBorder(null);
                        }
                        else
                        {
                            tFieldUsername.setBorder(BorderFactory.createLineBorder(DesignLayout.T_FIELD_BORDER_RED));
                        }                        
                    }
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }

            }
        });
        tFieldUsername.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    if (UserHandler.isUsernameAvailable(userObject) == true)
                    {
                        int altered = control.UserControl.updateUser(userObject);
                        if (altered > 0)
                        {
                            currentUser = UserHandler.getUserByID(currentUser.getId());
                        }
                        else
                        {
                            tFieldUsername.setText(currentUser.getUsername());
                        }                        
                    }
                    else
                    {                        
                        userObject.setUsername(currentUser.getUsername());
                        tFieldUsername.setText(userObject.getUsername());
                        
                    }
                    tFieldUsername.setEditable(false);
                    tFieldUsername.setForeground(Color.BLACK);
                    tFieldUsername.getCaret().setVisible(false);
                    tFieldUsername.setBorder(null);
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }
            }
        });
        add(tFieldUsername);
        // Username Field End
        
        // Email Field Begin
        tFieldEmail = new JTextField(user.getEmail());
        tFieldEmail.setBounds(10, 30, 240, 20);
        tFieldEmail.setFont(DesignLayout.STANDARD.deriveFont(12f));
        tFieldEmail.setBorder(null);
        tFieldEmail.setEditable(false);
        tFieldEmail.setOpaque(false);
        tFieldEmail.addMouseListener(new MouseAdapter() 
        {
            @Override
            public void mouseReleased(MouseEvent evt)
            {
                tFieldEmail.setEditable(true);
                tFieldEmail.setForeground(Color.ORANGE);
                tFieldEmail.getCaret().setVisible(true);
            }
        });
        tFieldEmail.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                try
                {
                    boolean emailAvailable = false;
                    userObject.setEmail(tFieldEmail.getText());
                    if (tFieldEmail.getText().length() > 0)
                    {
                        emailAvailable = UserHandler.isEmailAvailable(userObject);
                    }
                    else
                    {
                        emailAvailable = false;
                    }
                    if (emailAvailable == true)
                    {
                        tFieldEmail.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                    }
                    else
                    {
                        if (currentUser.getEmail().equals(userObject.getEmail()))
                        {
                            tFieldEmail.setBorder(null);
                        }
                        else
                        {
                            tFieldEmail.setBorder(BorderFactory.createLineBorder(DesignLayout.T_FIELD_BORDER_RED));
                        }                        
                    }
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }
            }
        });
        tFieldEmail.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    if (UserHandler.isEmailAvailable(userObject) == true)
                    {
                        int altered = control.UserControl.updateUser(userObject);
                        if (altered > 0)
                        {                            
                            currentUser = UserHandler.getUserByID(currentUser.getId());
                        }
                        else
                        {
                            tFieldEmail.setText(userObject.getEmail());
                        }                        
                    }
                    else
                    {                        
                        userObject.setEmail(currentUser.getEmail());
                        tFieldEmail.setText(userObject.getEmail());
                    }
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }
                tFieldEmail.setEditable(false);
                tFieldEmail.setForeground(Color.BLACK);
                tFieldEmail.getCaret().setVisible(false);
                tFieldEmail.setBorder(null);
            }
        });
        add(tFieldEmail);
        // Email Field End
        
        // Access Level Begin
        lblAccess = new JLabel("<html><b>Adgangsniveau: </b>"+switchLevelToString(currentUser.getAccessLevel())+"</html>");
        lblAccess.setBounds(10, 55, 240, 20);
        lblAccess.setFont(DesignLayout.STANDARD.deriveFont(12f));
        lblAccess.addMouseListener(new MouseAdapter() 
        {
            @Override
            public void mouseReleased(MouseEvent evt)
            {
                btnNewPassword.setVisible(false);
                newAccessLevelPanel.setVisible(true);
            }
        });
        add(lblAccess);
        // Access Level End
        
        // New Password Button Begin
        btnNewPassword = new JButton("ændré adgangskode");
        btnNewPassword.setBounds(55, 85, 140, 30);
        btnNewPassword.setBorder(DesignLayout.T_FIELD_RED);
        btnNewPassword.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        btnNewPassword.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnNewPassword.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                btnNewPassword.setVisible(false);
                newPasswordPanel.setVisible(true);
            }
        });
        add(btnNewPassword);
        // New Password Button End
        
        setBorder(DesignLayout.T_FIELD_RED);
    }
    
    private JPanel newPasswordPanel()
    {
        final JPanel panel = new JPanel(null);
        panel.setBounds(1, 1, 258, 123);
        panel.setBackground(Color.WHITE);
        panel.addComponentListener(new ComponentAdapter() 
        {
            @Override
            public void componentShown(ComponentEvent e)
            {
                pFieldNewPassword.setText("");
                pFieldNewPasswordRepeat.setText("");
                lblPasswordMessage.setText("");
            }
        });
        
        JButton btnClose = new JButton("x");
        btnClose.setBounds(233, 6, 20, 20);
        btnClose.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnClose.setForeground(DesignLayout.T_FIELD_BORDER_RED);
        btnClose.setBackground(Color.WHITE);
        btnClose.setBorder(BorderFactory.createEmptyBorder());
        btnClose.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                btnNewPassword.setVisible(true);
                newPasswordPanel.setVisible(false);
            }
        });
        
        JLabel lblPassword = new JLabel("Ny Adgangskode");
        lblPassword.setBounds(10, 10, 238, 20);
        lblPassword.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        
        pFieldNewPassword = new JPasswordField();
        pFieldNewPassword.setBounds(10, 30, 238, 20);
        pFieldNewPassword.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        pFieldNewPassword.setBorder(DesignLayout.T_FIELD_RED);
        pFieldNewPassword.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        pFieldNewPassword.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                arePasswordsEqual();
            }
        });
        
        JLabel lblPasswordRepeat = new JLabel("Gentag Ny Adgangskode");
        lblPasswordRepeat.setBounds(10, 50, 238, 20);
        lblPasswordRepeat.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        
        pFieldNewPasswordRepeat = new JPasswordField();
        pFieldNewPasswordRepeat.setBounds(10, 70, 238, 20);
        pFieldNewPasswordRepeat.setFont(DesignLayout.STANDARD.deriveFont(Font.BOLD, 12f));
        pFieldNewPasswordRepeat.setBorder(DesignLayout.T_FIELD_RED);
        pFieldNewPasswordRepeat.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        pFieldNewPasswordRepeat.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyReleased(KeyEvent e)
            {
                arePasswordsEqual();
            }
        });
        
        lblPasswordMessage = new JLabel("", JLabel.RIGHT);
        lblPasswordMessage.setBounds(1, 97, 190, 20);
        lblPasswordMessage.setFont(DesignLayout.STANDARD.deriveFont(12f));
        
        btnAlterPassword = new JButton("send");
        btnAlterPassword.setBounds(198, 97, 50, 20);
        btnAlterPassword.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnAlterPassword.setBorder(DesignLayout.T_FIELD_RED);
        btnAlterPassword.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        btnAlterPassword.setEnabled(false);
        btnAlterPassword.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (arePasswordsEqual() == true)
                {
                    try
                    {
                        String newPassword = String.valueOf(pFieldNewPasswordRepeat.getPassword()); // Get typed in new password
                        userObject.setPassword(newPassword);                                        // set password to user object
                        int altered = control.UserControl.updateUser(userObject);                   // changed password in database
                        
                        if (altered > 0)
                        {
                            currentUser = UserHandler.getUserByID(currentUser.getId());
                            lblPasswordMessage.setText("adgangskoden blev ændret");
                            lblPasswordMessage.setForeground(new Color(243, 109, 75));
                        }
                        else
                        {
                            lblPasswordMessage.setText("der opstod en fejl");
                            lblPasswordMessage.setForeground(DesignLayout.T_FIELD_BORDER_RED);
                        }
                    } 
                    catch (SQLException ex)
                    {
                        ExceptionManager.handleSQLException(ex);
                    } 
                    catch (ClassNotFoundException ex)
                    {
                        ExceptionManager.handleClassNotFoundException(ex);
                    }
                }
            }
        });
        
        panel.add(btnClose);
        panel.add(lblPassword);
        panel.add(pFieldNewPassword);
        panel.add(lblPasswordRepeat);
        panel.add(pFieldNewPasswordRepeat);
        panel.add(btnAlterPassword);
        panel.add(lblPasswordMessage);
        
        return panel;
    }
    
    private JPanel changeAccessLevel()
    {
        final JPanel panel = new JPanel(null);
        panel.setBounds(1, 1, 258, 123);
        panel.setBackground(Color.WHITE);
        
        JButton btnClose = new JButton("x");
        btnClose.setBounds(233, 6, 20, 20);
        btnClose.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnClose.setForeground(DesignLayout.T_FIELD_BORDER_RED);
        btnClose.setBackground(Color.WHITE);
        btnClose.setBorder(BorderFactory.createEmptyBorder());
        btnClose.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                btnNewPassword.setVisible(true);
                newAccessLevelPanel.setVisible(false);
            }
        });
        
        ActionListener actionListener =
        (
            new ActionListener() 
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    userObject.setAccessLevel(getUserAccessLevel(e));
                }
            }
        );
        
        ButtonGroup btnGroup = new ButtonGroup();
        
        JRadioButton rSalesman = new JRadioButton("Sælger");
        rSalesman.addActionListener(actionListener);
        rSalesman.setBounds(10, 30, 150, 20);
        rSalesman.setFont(DesignLayout.STANDARD);
        rSalesman.setOpaque(false);
        if (userObject.getAccessLevel() == 1)
        {
            rSalesman.setSelected(true);
        }
        
        JRadioButton rAdmin = new JRadioButton("Admin");
        rAdmin.addActionListener(actionListener);
        rAdmin.setBounds(10, 50, 150, 20);
        rAdmin.setFont(DesignLayout.STANDARD);
        rAdmin.setOpaque(false);
        if (userObject.getAccessLevel() == 2)
        {
            rAdmin.setSelected(true);
        }
        
        JRadioButton rDeveloper = new JRadioButton("Udvikler");
        rDeveloper.addActionListener(actionListener);
        rDeveloper.setBounds(10, 70, 150, 20);
        rDeveloper.setFont(DesignLayout.STANDARD);
        rDeveloper.setOpaque(false);
        if (userObject.getAccessLevel() == 3)
        {
            rDeveloper.setSelected(true);
        }
        
        btnGroup.add(rSalesman);
        btnGroup.add(rAdmin);
        btnGroup.add(rDeveloper);
        
        JButton btnSend=  new JButton("send");
        btnSend.setBounds(198, 97, 50, 20);
        btnSend.setFont(DesignLayout.STANDARD.deriveFont(12f));
        btnSend.setBorder(DesignLayout.T_FIELD_RED);
        btnSend.setBackground(DesignLayout.T_FIELD_BG_COLOR);
        btnSend.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    int altered = control.UserControl.updateUser(userObject);                   // changed password in database

                    if (altered > 0)
                    {
                        btnNewPassword.setVisible(true);
                        newAccessLevelPanel.setVisible(false);
                        adminUser.getAdminUserList().buildExistingScrollPanel("WHERE id = "+userObject.getId(), "", "");

                    }
                    else
                    {
                        btnNewPassword.setVisible(true);
                        newAccessLevelPanel.setVisible(false);
                        adminUser.getAdminUserList().buildExistingScrollPanel("WHERE id = "+userObject.getId(), "", "");
                    }
                } 
                catch (SQLException ex)
                {
                    ExceptionManager.handleSQLException(ex);
                } 
                catch (ClassNotFoundException ex)
                {
                    ExceptionManager.handleClassNotFoundException(ex);
                }
            }
        });
        
        panel.add(rSalesman);
        panel.add(rAdmin);
        panel.add(rDeveloper);
        panel.add(btnClose);
        panel.add(btnSend);
        
        return panel;
    }
    
    private int getUserAccessLevel(ActionEvent e)
    {
        JRadioButton temp = (JRadioButton) e.getSource();
        if (temp.getText().equals("Sælger")) return 1;
        if (temp.getText().equals("Admin")) return 2;
        if (temp.getText().equals("Udvikler")) return 3;
        else return 0;
    }
    
    
    private boolean arePasswordsEqual()
    {
        boolean answer = false;
        
        if (
                String.valueOf(pFieldNewPassword.getPassword()).equals(String.valueOf(pFieldNewPasswordRepeat.getPassword())) &&
                String.valueOf(pFieldNewPassword.getPassword()).length() > 0
            )
        {
            lblPasswordMessage.setText("adgangskoder ens");
            btnAlterPassword.setEnabled(true);
            lblPasswordMessage.setForeground(new Color(0, 100, 0));
            answer = true;
        }
        else
        {
            lblPasswordMessage.setText("adgangskoder ikke ens");
            lblPasswordMessage.setForeground(DesignLayout.T_FIELD_BORDER_RED);
            btnAlterPassword.setEnabled(false);
            answer = false;
        }
        return answer;
    }
    
    private String switchLevelToString(int level)
    {
        String strLevel = "";
        
        switch (level)
        {
            case 1:
                strLevel = "Sælger";
            break;
            case 2:
                strLevel = "Admin";
            break;
            case 3:
                strLevel = "Udvikler";
            break;
        }
        
        return strLevel;
    }
}